package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.Setmeal;
import com.itheima.reggie.domain.SetmealDish;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.sercice.CategoryService;
import com.itheima.reggie.sercice.SetmealDishService;
import com.itheima.reggie.sercice.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    //修改前的数据回显
    @GetMapping("/{id}")
    public R getSetmealById(@PathVariable Long id) {
        //获取套餐表中的信息
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);

        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getId() != null, SetmealDish::getSetmealId, setmeal.getId());
        List<SetmealDish> list = setmealDishService.list(wrapper);
        setmealDto.setSetmealDishes(list);

        return R.success(setmealDto);
    }

    //修改套餐数据
    @CacheEvict(value = "setmeal",allEntries = true)
    @PutMapping
    public R updateSetmeal(@RequestBody SetmealDto setmealDto) {
        setmealService.updateById(setmealDto);
        Long setmealId = setmealDto.getId();
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, setmealId);
        setmealDishService.remove(wrapper);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealId);
        }
        setmealDishService.saveBatch(setmealDishes);

        return R.success("成功");
    }

    //修改套餐状态
    @CacheEvict(value = "setmeal",allEntries = true)
    @PostMapping("/status/{status}")
    public R update(@PathVariable Integer status, @RequestParam List<Long> ids) {
        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }

        return R.success("修改成功");
    }


    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmeal",allEntries = true)
    @DeleteMapping
    public R del(@RequestParam List<Long> ids) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getStatus, 1);
        wrapper.in(Setmeal::getId, ids);
        //如果符合条件的套餐数量大于0 就代表有的套餐在售  就不能删除
        int count = setmealService.count(wrapper);
        if (count > 0) {
            //如果不能删除，抛出一个业务异常
            throw new CustomException("套餐正在售卖中，不能删除");
        }
        //可以删除
        setmealService.removeByIds(ids);

        //构建一个条件构造器
        LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
        //查看可以删除套餐内的菜品
        wrapper1.in(SetmealDish::getSetmealId, ids);

        setmealDishService.remove(wrapper1);
        return R.success("删除成功");
    }


    /**
     * 新增套餐接口
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmeal",allEntries = true)
    @PostMapping
    public R saveSetmeal(@RequestBody SetmealDto setmealDto) {
        //把setmeal表的数据保存到sermealDto表中
        setmealService.save(setmealDto);
        //获取setmealDishes集合
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //遍历集合  给mealId(套餐id) 赋值
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }

        setmealDishService.saveBatch(setmealDishes);

        return R.success("添加成功");
    }

    //分页查询
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        List<SetmealDto> setmealDtos = new ArrayList<>();

        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Setmeal::getName, name);
        wrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo, wrapper);

        int total = (int) pageInfo.getTotal();
        Map map = new HashMap();

        BeanUtil.copyProperties(pageInfo, setmealDtos);

        List<Setmeal> records = pageInfo.getRecords();
        for (Setmeal setmeal : records) {
            //获取套餐类型id
            Long categoryId = setmeal.getCategoryId();
            //根据套餐类型获取套餐类型名称
            /*Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();*/
            String categoryName = categoryService.getById(categoryId).getName();
            //创建一个setmealDto对象
            SetmealDto setmealDto = new SetmealDto();
            //把套餐类型名称set进去
            setmealDto.setCategoryName(categoryName);
            BeanUtil.copyProperties(setmeal, setmealDto);
            setmealDtos.add(setmealDto);

        }
        map.put("total", total);
        map.put("records", setmealDtos);
        return R.success(map);
    }

    //接口三：根据套餐分类id查询该套餐分类下的套餐

    @Cacheable(value = "setmeal", key = "#setmeal.categoryId + '_' + #setmeal.status")
    @GetMapping("/list")
    public R list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Setmeal::getCategoryId, setmeal.getCategoryId());
        wrapper.eq(Setmeal::getStatus, setmeal.getStatus());
        List<Setmeal> list = setmealService.list(wrapper);
        return R.success(list);

    }

   /* //
    @GetMapping("/dish/{id}")
    public R tu(@PathVariable Long id) {
        Setmeal setmeal = setmealService.getById(id);
        String image = setmeal.getImage();

        return R.success(image);
    }*/

}
